from django import forms
from web.forms.bootstrap import BootStrapForm
from web.models import Project
from web import models
from django.core.exceptions import ValidationError
from web.forms.widgets import ColorRadioSelect

class ProjectModelForm(BootStrapForm,forms.ModelForm):
    bootstrap_class_exclude = ['color']

    class Meta:
        model = models.Project
        fields = ['name','color','desc']
        widgets = {
            'desc':forms.Textarea,
            'color':ColorRadioSelect(attrs={'class':'color-radio'}),
        }
    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request

    def clean_name(self):
        name = self.cleaned_data['name']
        #当前用户是否已创建此项目？
        exists = models.Project.objects.filter(name=name,creator = self.request.tracer.user).exists()
        if exists:
            raise ValidationError('项目已存在')
        #是否还有额度？

        #当前已使用额度
        count = models.Project.objects.filter(creator = self.request.tracer.user).count()
        #判断当前已使用额度是不是大于最高额度
        if count>=self.request.tracer.price_policy.project_num:
            raise ValidationError('额度拉满了！你快升级吧')
        return name
